<?php

namespace app\stock\controller;

use think\Controller;

class Admin extends Controller
{
    protected $AdminModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->AdminModel = model('Admin');
    }

    public function wxlogin()
    {
        $code = $this->request->param('code', '', 'trim');

        $code2Session = $this->code2Session($code);

        if ($code2Session['code'] === 0) {
            $this->error($code2Session['msg']);
        }

        $openid = isset($code2Session['data']['openid']) ? $code2Session['data']['openid'] : '';

        if (!$openid) {
            $this->error('openid未知');
        }

        $Admin = $this->AdminModel->where(['openid' => $openid])->find();

        if (!$Admin) {
            $this->error('请先绑定账号', null, ['bind' => 'bind', 'openid' => $openid]);
        }

        if ($Admin['status'] != 'normal') {
            $this->error('当前账号已禁用');
        }

        $this->success('登录成功', null, $Admin);
    }

    public function bind()
    {
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $openid = $this->request->param('openid', '', 'trim');

        // 通过管理员的用户名查询数据库，如果有该管理员就更新openid，否则创建一个管理员
        $Admin = $this->AdminModel->where(['username' => $username])->find();

        if (!$Admin) {
            $this->error('用户名错误');
        }

        if ($Admin['status'] != 'normal') {
            $this->error('当前账号已禁用');
        }

        if (empty($openid)) {
            $this->error('openid未知');
        }

        // 密码加密
        $password = md5(md5($password) . $Admin['salt']);

        // 判断密码是否正确
        if ($password != $Admin['password']) {
            $this->error('密码错误');
        }

        $data = [
            'id' => $Admin['id'],
            'openid' => $openid,
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            $this->error('绑定失败');
        } else {

            $Admin = $this->AdminModel->find($Admin['id']);

            $this->success('绑定成功', null, $Admin);
        }
    }

    public function login()
    {
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');

        $Admin = $this->AdminModel->where(['username' => $username])->find();

        if (!$Admin) {
            $this->error('当前账号不存在');
        }

        $password = md5(md5($password) . $Admin['salt']);

        if ($password != $Admin['password']) {
            $this->error('密码错误');
        }

        if ($Admin['status'] != 'normal') {
            $this->error('当前账号已禁用');
        }

        $this->success('登录成功', null, $Admin);
    }

    public function unbinding()
    {
        $adminid = $this->request->param('adminid', '', 'trim');

        $Admin = $this->AdminModel->find($adminid);

        if (!$Admin) {
            $this->error('当前账号不存在');
        }

        if (empty($Admin['openid'])) {
            $this->error('当前账号未绑定微信小程序');
        }

        $data = [
            'id' => $adminid,
            'openid' => null
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            $this->error('解绑失败');
        } else {
            $this->success('解绑成功');
        }
    }

    public function upload()
    {
        $adminid = $this->request->param('adminid', 0, 'trim');

        $Admin = $this->AdminModel->find($adminid);

        if (!$Admin) {
            $this->error('该管理员不存在');
        }

        $avatar = build_upload('avatar');

        if ($avatar['code'] === 0) {
            $this->error($avatar['msg']);
        }

        $data = [
            'id' => $Admin['id'],
            'avatar' => $avatar['data']
        ];

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
            $this->error('更新头像失败');
        } else {
            @is_file('.' . $Admin['avatar']) && @unlink('.' . $Admin['avatar']);
            $Admin = $this->AdminModel->find($Admin['id']);
            $this->success('更新头像成功', null, $Admin);
        }
    }

    public function profile()
    {
        $params = $this->request->param();

        $Admin = $this->AdminModel->find($params['id']);

        if (!$Admin) {
            $this->error('管理员不存在');
        }

        $data = [
            'id' => $params['id'],
            'nickname' => $params['nickname'],
            'mobile' => $params['mobile'],
            'email' => $params['email']
        ];

        if (!empty($params['password'])) {
            $salt = build_ranstr(6);

            $password = md5(md5($params['password']) . $salt);

            $data['salt'] = $salt;

            $data['password'] = $password;
        }

        $result = $this->AdminModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            $this->error('修改资料失败');
        } else {

            $Admin = $this->AdminModel->find($params['id']);

            $this->success('修改资料成功', null, $Admin);
        }
    }

    protected function code2Session($code)
    {
        $result = [
            'code' => 0,
            'msg' => '登录凭证未知',
            'data' => null,
        ];

        if ($code) {
            // 小程序appid(改成自己的)
            $appid = 'wx8de9d19aab6c401a';

            // 小程序密钥(改成自己的)
            $AppSecret = '1d5880383f8ed68f1561e1b7fe010d48';

            $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$AppSecret&js_code=$code&grant_type=authorization_code";

            $res = $this->httpRequest($apiUrl);

            $res = json_decode($res, true);

            $result = [
                'code' => 1,
                'msg' => '获取登录凭证成功',
                'data' => $res
            ];

            return $result;
        }

        return $result;
    }

    protected function httpRequest($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }
}
